import { PermissionsAndroid, Platform } from "react-native";
import { init, Geolocation } from "react-native-amap-geolocation";
import axios from "axios";
import { rootStore } from '../../store/index';

class Geo {
  async initGeo() {
    if (Platform.OS === "android") {
     // await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION);
        await PermissionsAndroid.requestMultiple([
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
        PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
        PermissionsAndroid.PERMISSIONS.ACCESS_BACKGROUND_LOCATION,
        PermissionsAndroid.PERMISSIONS.ACCESS_WIFI_STATE,
        PermissionsAndroid.PERMISSIONS.ACCESS_LOCATION_EXTRA_COMMANDS,
        PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
      ]);
    }
    await init({
      // 来自于 高德地图中的第二个应用 android 应用key
      ios: "66b0a941e8a77da6cbff3a62a23938e4",
      android: "66b0a941e8a77da6cbff3a62a23938e4"
    });
    return Promise.resolve();
  }
  async getCurrentPosition() {
    return new Promise((resolve, reject) => {
      Geolocation.getCurrentPosition(({ coords }) => {
        resolve(coords);
      }, reject);
    })
  }
  async getCityByLocation() {
    console.error("开始定位",1111);
    let time = 0;
    let latitudeObj = {};
    try { 
      latitudeObj = await this.getCurrentPosition();
      console.error("开始定位", latitudeObj);
      if(!latitudeObj.longitude) {
        time++; 
        console.error("time", time);
        if(time > 5) {
          return Promise.reject("定位失败");
        }
        latitudeObj =  await this.getCurrentPosition();
      } else {
        // console.error("开始定位", latitudeObj);
        const res = await axios.get("https://restapi.amap.com/v3/geocode/regeo", {
          // key  高德地图中第一个应用的key
          params: { 
            location: `${latitudeObj.longitude},${latitudeObj.latitude}`, 
            key: "0c50cf67372e578bceaffb035d616a3c", 
            radius: 10,
            extensions: "all",
            roadlevel: 0,
          },
        });
        // const res = await axios.get("https://restapi.amap.com/v3/geocode/regeo?&key=0c50cf67372e578bceaffb035d616a3c&location=116.481488,39.990464&poitype=商务写字楼&radius=1000&extensions=all&roadlevel=0")
        console.error("开始定位", res.data, time);
        const info = res.data.regeocode;
        const location = {
          address: '',
          longitude: latitudeObj.longitude,
          latitude: latitudeObj.latitude
        };
        if (info && info.formatted_address) {
          location.address = info.formatted_address;
        }
        rootStore.userInfo.setLocation({...location});
        return Promise.resolve(res.data);
      }
    } catch(error) {
      console.error("定位失败", error);
    }
  }
}


export default new Geo();